<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="仪表名称" prop="deptName">
                <el-input
                    v-model="queryParams.search"
                    placeholder="请输入仪表名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="所属区片：" prop="community_id">
                <el-select v-model="queryParams.community_id"  @change="changeMachine" placeholder="请选择区片" size="small"  >
                    <el-option v-for="(item, index) in communityList" :key="index" :label="item.title"
                               :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属区片：" prop="apparatus_id">
                <el-select v-model="queryParams.apparatus_id"  placeholder="请选择水机" size="small"  >
                    <el-option v-for="(item, index) in apparatusList" :key="index" :label="item.title"
                               :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="类型" clearable>
                    <el-option
                        v-for="dict in dict.type.sys_expenses_master_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="状态" clearable>
                    <el-option
                        v-for="dict in dict.type.sys_expenses_master_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table  v-loading="loading" :data="masterLists" border fit highlight-current-row>
            <el-table-column type="selection" width="55" bo align="center" label-width="100px" />
            <el-table-column label="编号" align="center" prop="master_id"  width="50"/>
            <el-table-column label="所属水机" align="center" prop="water_id" >
                <template slot-scope="{row}">
                    {{ row.water_device_info? row.water_device_info.water_title : "" }}
                </template>
            </el-table-column>
            <el-table-column label="仪表名称" align="center" prop="master_name" :show-overflow-tooltip="true" />
            <el-table-column label="仪表编号" align="center" prop="master_sn" :show-overflow-tooltip="true" />
            <el-table-column prop="type" align="center" label="类型" width="100">
                <template slot-scope="{row}">
                    <dict-tag :options="dict.type.sys_expenses_master_type" :value="row.type"/>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                <template slot-scope="{row}">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(row)"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.limit"
            @pagination="getList"
        />

        <!-- 添加或修改部门对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="所属区片：" prop="community_id">
                    <el-select v-model="form.community_id"  @change="changeMachine" placeholder="请选择区片" size="small"  >
                        <el-option v-for="(item, index) in communityList" :key="index" :label="item.title"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属水机：" prop="apparatus_id">
                    <el-select v-model="form.apparatus_id"  placeholder="请选择水机" size="small"  >
                        <el-option v-for="(item, index) in apparatusList" :key="index" :label="item.title"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 检测项管理 -->
                <el-card shadow="never">
                        <div slot="header">
                            <span>检测项目</span>
                            <el-button type="text" icon="el-icon-circle-plus" @click="showItemSelector = true">添加检测项</el-button>
                        </div>
                        <div v-for="(item, idx) in selectedItems" :key="item.item_id">
                            <el-form-item :label="item.item_name" :prop="`records[${idx}].value`" :rules="getItemRules(item)">

                                <!-- 数值类型 -->
                                <el-input-number v-if="item.check_type === 'number'" v-model="item.min" :precision="2">
<!--                                    <template slot="append">{{ item.data_unit }}</template>-->
                                </el-input-number>
                                <el-input-number v-if="item.check_type === 'number'" v-model="item.max"   :precision="2">
                                    <template slot="append">{{ item.data_unit }}</template>
                                </el-input-number>
                                <!-- 单选类型 -->
                                <el-radio-group v-if="item.check_type === 'radio'" v-model="item.value">
                                    <el-radio v-for="opt in item.options" :key="opt" :label="opt"/>
                                </el-radio-group>
                                <el-radio-group v-if="item.check_type === 'enum'" v-model="item.value">
                                    <el-radio v-for="opt in item.options" :key="opt" :label="opt"/>
                                </el-radio-group>

                                <!-- 开关类型 -->
                                <el-switch v-if="item.check_type === 'switch'" v-model="item.value" active-text="正常" inactive-text="异常"/>

                                <!-- 文本类型 -->
                                <el-input v-if="item.check_type === 'text'" v-model="item.value" :placeholder="`请输入${item.item_name}`"/>

                                <el-button
                                    type="danger"
                                    icon="el-icon-delete"
                                    circle
                                    @click="removeItem(idx)"
                                    class="ml-10"
                                />
                            </el-form-item>
                        </div>
                    </el-card>


                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 检测项选择器 -->
        <el-dialog title="选择检测项" :visible.sync="showItemSelector" width="900px"  >
            <el-transfer
                style="text-align: left; display: inline-block"
                v-model="selectedItemIds"
                filterable
                :titles="['可选项目', '已选项目']"
                :button-texts="['可选项目', '已选项目']"
                :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
                @change="handleChange"
                :data="checkItems"
                :props="{ key: 'item_id', label: 'item_name' }"
            >
            </el-transfer>

        </el-dialog>
    </div>
</template>
<script>


import { getAllCom} from "@/api/grzq/community.js";
import {
    getApparatusAllList,
} from "@/api/grzq/apparatus.js";
import {
    createMaintenance,
    getMaintenanceDetail,
    getMaintenanceList,
    updateMaintenance
} from "@/api/property/maintenance";
import {getCheckCategoryItemSelectList} from "@/api/property/check/category";
import {getCheckItemSelectList} from "@/api/property/check/item";

export default {
    name: "company",
    dicts:['sys_expenses_master_type','sys_expenses_master_status'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 表格数据
            masterLists: [],
            communityList: [],
            apparatusList: [],
            // 检测项相关
            value: [],
            showItemSelector: false,
            selectedItemIds: [],
            checkItems: [], // 所有检测项
            itemList:[],

            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否展开，默认全部展开
            isExpandAll: true,
            // 重新渲染表格状态
            refreshTable: true,
            // 查询参数
            queryParams: {
                search: undefined,
                community_id: undefined,
                type: undefined,
                apparatus_id: undefined,
                status: undefined,
                page: 1,
                limit: 10,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                community_id: [
                    { required: true, message: "请选择片区", trigger: "blur" }
                ],
                apparatus_id: [
                    { required: true, message: "请选择水机", trigger: "blur" }
                ],
                master_name: [
                    { required: true, message: "仪表名称不能为空", trigger: "blur" }
                ],
                master_sn: [
                    { required: true, message: "仪表编码不能为空", trigger: "blur" }
                ],
                price: [
                    { required: true, message: "水/电单价不能为空", trigger: "blur" }
                ],
                type: [
                    { required: true, message: "单价不能为空", trigger: "blur" }
                ],
            },

        };
    },
    watch:{
        selectedItemIds: {
            handler(newVal) {
                console.log("selectedItemIds 更新:", newVal);
            },
            deep: true // 深度监听数组元素变化
        },
    },
    computed: {
        availableItems() {
            console.log("307",this.checkItems)
            return this.checkItems.filter(item =>
                !this.selectedItemIds.includes(item.item_id)
            )
        },
        // 已选检测项数据
        selectedItems() {
            console.log("315",this.selectedItemIds)
            return this.selectedItemIds.map(id => {
                const item = this.checkItems.find(i => i.item_id === id);
                console.log("item",item)
                return {
                    ...item,
                    value: this.getDefaultValue(item),
                    // 确保数值类型转换
                    min: Number(item.min),
                    max: Number(item.max)
                };
            });
        }
    },
    created() {
        this.getList();
        this.changeCheckItem();
    },
    methods: {
        handleChange(value, direction, movedKeys) {
            console.log(value, direction, movedKeys);
        },

        // 获取检测项默认值
        getDefaultValue(item) {
            switch(item.check_type) {
                case 'bool': return item.min_value || 0
                case 'number': return item.standard_value || []
                case 'enum': return item.options || 0
                case 'radio': return JSON.parse(item.options)[0]
                case 'switch': return true
                default: return ''
            }
        },
        /** 查询部门列表 */
        async getList() {
            let that = this;
            that.loading = true;
            const {data, status, msg} = await getMaintenanceList(this.queryParams);
            that.masterLists = data.data;
            that.loading = false;
            that.total = data.total;
            that.queryParams.limit = data.per_page || 10;

        },
        //片区
        async getAllCom() {
            const res = await getAllCom();
            this.communityList = res.data;
            console.log("this.communityList",this.communityList)
        },
        //片区-水机
        async changeMachine(community_id) {
            const res = await getApparatusAllList({'community_id':community_id});
            this.apparatusList = res.data;
            console.log("this.apparatusList",this.apparatusList)
        },
        //片区-水机
        // async changeItem() {
        //     const res = await getCheckCategoryItemSelectList();
        //     this.itemList = res.data;
        //
        //     this.itemList = this.handleTree(res.data, "category_id", "parent_id");
        //     console.log("this.itemList",this.itemList)
        // },
        //片区-水机
        async changeCheckItem() {
            const res = await getCheckItemSelectList();
            // this.checkItems = res.data;
            this.checkItems = res.data.map(item => ({
                ...item,
                check_type: item.check_type, // 统一字段命名
                options: item.options ? JSON.parse(item.options) : [],
                standard_value: item.standard_value ? JSON.parse(item.standard_value) : []
            }));
            console.log("this.checkItems ",this.checkItems )

        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                master_id: undefined,
                apparatus_id: undefined,
                meter_name: undefined,
                meter_sn: undefined,
                price: undefined,
                end_day: undefined,
                remark: undefined,
                amount_total: undefined,
                status: "0"
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd(row) {
            this.reset();
            this.open = true;
            this.title = "添加数据";
            this.form.dictType = this.queryParams.dictType;
            this.getAllCom()
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.getAllCom()
            const master_id = row.master_id || this.ids
            getMaintenanceDetail({master_id:master_id}).then(response => {
                let data= response.data;
                this.changeMachine(data.community_id);
                this.form = data;
                this.form.status = data.status.toString();
                this.open = true;
                this.title = "修改";
            });
        },
        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.master_id != undefined) {
                        updateMaintenance(this.form).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        createMaintenance(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        removeItem(index){

        },
        // 生成动态验证规则
        getItemRules(item) {
            const rules = []
            if (item.is_required) {
                rules.push({ required: true, message: '该项为必填项' })
            }
            if (item.item_type === 'number') {
                rules.push({
                    validator: (rule, value, callback) => {
                        if (value < item.min_value || value > item.max_value) {
                            callback(new Error(`值应在${item.min_value}-${item.max_value}之间`))
                        } else {
                            callback()
                        }
                    }
                })
            }
            return rules
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            this.confirm('是否确认删除名称为"' + row.meter_name + '"的数据项？').then(function() {
                return delMaster({read_id:row.read_id});
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => {});
        }
    }
};
</script>
